<?php
/**
 * RoleRegistry
 *
 * @category	acl
 * @package		dayscript.acl.role
 * @subpackage
 * @author		Zend Technologies USA Inc.
 * @copyright	Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
 * @license		http://framework.zend.com/license/new-bsd New BSD License
 * @version		$Id: Registry.php 16199 2009-06-21 18:42:43Z thomas $
 * @filesource
 * @link		http://www.dayscript.com
 * @link		{docsLink}
 * @uses
 * @since		1.0
 * @modifiedby	$LastChangedBy: Noel Marin $
 * @modified	$Date: 2009-09-17 $
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 */
namespace dayscript\acl\role;

/**
 * RoleRegistry
 *
 * Role registry data storage
 *
 * @category	acl
 * @package		dayscript.acl.role
 * @subpackage
 * @author		Zend Technologies USA Inc.
 * @copyright	Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
 * @license		http://framework.zend.com/license/new-bsd New BSD License
 * @version		$Id: Registry.php 16199 2009-06-21 18:42:43Z thomas $
 * @filesource
 * @link		http://www.dayscript.com
 * @link		{docsLink}
 * @uses		\dayscript\acl\role\RoleRegistry \dayscript\exception\Exception \dayscript\exception\ErrorCallerException
 * @since		1.0
 * @modifiedby	$LastChangedBy: Noel Marin $
 * @modified	$Date: 2009-09-17 $
 */
class RoleRegistry {
	
    /**
     * Internal Role registry data storage
     *
     * @var array
     */
    protected $_roles = array();

    /**
     * Adds a Role having an identifier unique to the registry
     *
     * The $parents parameter may be a reference to, or the string identifier for,
     * a Role existing in the registry, or $parents may be passed as an array of
     * these - mixing string identifiers and objects is ok - to indicate the Roles
     * from which the newly added Role will directly inherit.
     *
     * In order to resolve potential ambiguities with conflicting rules inherited
     * from different parents, the most recently added parent takes precedence over
     * parents that were previously added. In other words, the first parent added
     * will have the least priority, and the last parent added will have the
     * highest priority.
     *
     * @param  \dayscript\acl\role\Role              $role
     * @param  \dayscript\acl\role\Role|string|array $parents
     * @throws \dayscript\exception\ErrorCallerException
     * @return \dayscript\acl\role\RoleRegistry Provides a fluent interface
     */
    public function add(\dayscript\acl\role\Role $role, $parents = null){
        $roleId = $role->getRoleId();

        if ($this->has($roleId)) {
        	throw new \dayscript\exception\ErrorCallerException( "Role id '$roleId' already exists in the registry ", E_USER_ERROR );
        }

        $roleParents = array();

        if (null !== $parents) {
            if (!\is_array($parents)) {
                $parents = array($parents);
            }
            
            foreach ($parents as $parent) {
                try {
                    if ($parent instanceof \dayscript\acl\role\Role) {
                        $roleParentId = $parent->getRoleId();
                    } else {
                        $roleParentId = $parent;
                    }
                    $roleParent = $this->get($roleParentId);
                } catch (\dayscript\exception\Exception $e) {
                    throw new \dayscript\exception\ErrorCallerException( "Parent Role id '$roleParentId' does not exist ", E_USER_ERROR );
                }
                $roleParents[$roleParentId] = $roleParent;
                $this->_roles[$roleParentId]['children'][$roleId] = $role;
            }
        }

        $this->_roles[$roleId] = array(
            'instance' => $role,
            'parents'  => $roleParents,
            'children' => array()
            );

        return $this;
    }

    /**
     * Returns the identified Role
     *
     * The $role parameter can either be a Role or a Role identifier.
     *
     * @param  \dayscript\acl\role\Role|string $role
     * @throws \dayscript\exception\ErrorCallerException
     * @return \dayscript\acl\role\Role
     */
    public function get($role){
        if ($role instanceof \dayscript\acl\role\Role) {
            $roleId = $role->getRoleId();
        } else {
            $roleId = (string) $role;
        }

        if (!$this->has($role)) {
            throw new \dayscript\exception\ErrorCallerException( "Role '$roleId' not found ", E_USER_ERROR );
        }

        return $this->_roles[$roleId]['instance'];
    }

    /**
     * Returns true if and only if the Role exists in the registry
     *
     * The $role parameter can either be a Role or a Role identifier.
     *
     * @param  \dayscript\acl\role\Role|string $role
     * @return boolean
     */
    public function has($role){
        if ($role instanceof \dayscript\acl\role\Role) {
            $roleId = $role->getRoleId();
        } else {
            $roleId = (string) $role;
        }

        return isset($this->_roles[$roleId]);
    }

    /**
     * Returns an array of an existing Role's parents
     *
     * The array keys are the identifiers of the parent Roles, and the values are
     * the parent Role instances. The parent Roles are ordered in this array by
     * ascending priority. The highest priority parent Role, last in the array,
     * corresponds with the parent Role most recently added.
     *
     * If the Role does not have any parents, then an empty array is returned.
     *
     * @param  \dayscript\acl\role\Role|string $role
     * @uses   \dayscript\acl\role\RoleRegistry::get()
     * @return array
     */
    public function getParents($role){
        $roleId = $this->get($role)->getRoleId();

        return $this->_roles[$roleId]['parents'];
    }

    /**
     * Returns true if and only if $role inherits from $inherit
     *
     * Both parameters may be either a Role or a Role identifier. If
     * $onlyParents is true, then $role must inherit directly from
     * $inherit in order to return true. By default, this method looks
     * through the entire inheritance DAG to determine whether $role
     * inherits from $inherit through its ancestor Roles.
     *
     * @param  \dayscript\acl\role\Role|string $role
     * @param  \dayscript\acl\role\Role|string $inherit
     * @param  boolean                        $onlyParents
     * @throws \dayscript\exception\Exception
     * @return boolean
     */
    public function inherits($role, $inherit, $onlyParents = false){
        try {
            $roleId     = $this->get($role)->getRoleId();
            $inheritId = $this->get($inherit)->getRoleId();
        } catch (\dayscript\exception\Exception $e) {
            throw $e;
        }

        $inherits = isset($this->_roles[$roleId]['parents'][$inheritId]);

        if ($inherits || $onlyParents) {
            return $inherits;
        }

        foreach ($this->_roles[$roleId]['parents'] as $parentId => $parent) {
            if ($this->inherits($parentId, $inheritId)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Removes the Role from the registry
     *
     * The $role parameter can either be a Role or a Role identifier.
     *
     * @param  \dayscript\acl\role\Role|string $role
     * @throws \dayscript\exception\Exception
     * @return \dayscript\acl\role\RoleRegistry Provides a fluent interface
     */
    public function remove($role){
        try {
            $roleId = $this->get($role)->getRoleId();
        } catch (\dayscript\exception\Exception $e) {
            throw $e;
        }

        foreach ($this->_roles[$roleId]['children'] as $childId => $child) {
            unset($this->_roles[$childId]['parents'][$roleId]);
        }
        foreach ($this->_roles[$roleId]['parents'] as $parentId => $parent) {
            unset($this->_roles[$parentId]['children'][$roleId]);
        }

        unset($this->_roles[$roleId]);

        return $this;
    }

    /**
     * Removes all Roles from the registry
     *
     * @return \dayscript\acl\role\RoleRegistry Provides a fluent interface
     */
    public function removeAll(){
        $this->_roles = array();

        return $this;
    }
    
    /**
     * Returns Roles from the registry
     * 
     * @return array
     */
    public function getRoles(){
    	return $this->_roles;
    }

}